package com.zjitc.backend_shop.config;
import com.zjitc.backend_shop.security.JwtAuthenticationFilter;
import com.zjitc.backend_shop.security.LoginFailureHandler;
import com.zjitc.backend_shop.security.LoginSuccessHandler;
import com.zjitc.backend_shop.security.MyUserDetailServiceImpl;
import com.zjitc.backend_shop.utils.JsonLoginFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;


/*
    @author： 尤安托
    @date： 2025/4/11 14:02
*/
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig{
    @Autowired
    private LoginSuccessHandler loginSuccessHandler;
    @Autowired
    private LoginFailureHandler loginFailureHandler;
    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;


    private static final String URL_WHITELIST[] ={"/login","/logout","/home/**","/list","/static/**","admin/login"} ;


    // 密码编码器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    // 配置 AuthenticationManager
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
        return configuration.getAuthenticationManager();
    }



    @Bean
    public CorsConfigurationSource configurationSource() {
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();

        // 跨域配置
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedOrigins(Arrays.asList("http://localhost:8888","http://localhost:5173")); // 允许的请求来源
        corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); // 允许的请求方法
        corsConfiguration.setAllowedHeaders(Arrays.asList("*"));// 允许的请求头

        // 注册配置
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);
        return urlBasedCorsConfigurationSource;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http, AuthenticationManager authenticationManager) throws Exception {
//        JsonLoginFilter jsonLoginFilter = new JsonLoginFilter("/admin/login", authenticationManager);
//        jsonLoginFilter.setAuthenticationSuccessHandler(loginSuccessHandler);
//        jsonLoginFilter.setAuthenticationFailureHandler(loginFailureHandler);
        http
                .cors(cors -> cors.configurationSource(configurationSource()))
                .csrf(csrf -> csrf.disable())
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers(URL_WHITELIST).permitAll() // 允许访问公共路径
                        .requestMatchers("/admin/**").hasRole("ADMIN")
                        .anyRequest().authenticated() // 其他请求需要身份验证
                )
//                .addFilterBefore(jsonLoginFilter, UsernamePasswordAuthenticationFilter.class) // 添加自定义过滤器
                .formLogin(formLogin -> formLogin
                        .loginPage("http://localhost:8888/login")
//                        .loginProcessingUrl("/admin/login")// 处理登录请求的URL
                        .permitAll() // 允许所有用户访问登录页面
//                        .successHandler(loginSuccessHandler)
//                        .failureHandler(loginFailureHandler)
                )
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                .logout(logout -> logout.permitAll()); // 允许注销操作
        return http.build();
    }
}